﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.WebEncoders;
using Newtonsoft.Json;
using YesBlog.Application.User;
using YesBlog.Domain;
using YesBlog.Framework.Attribute;
using YesBlog.Framework.Extension;
using YesBlog.Infrastructure.Context;
using YesBlog.Repository;


namespace YesBlog.Web
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
              .SetBasePath(env.ContentRootPath)
              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
              .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<YesDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Conn"), b => b.UseRowNumberForPaging()));


            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(options => {
                //options.Cookie.Domain = ".domain.dev";
                options.Cookie.Name = "LoginInfo";
                options.Cookie.Path = "/";
                options.LoginPath = "/Admin/User/Login";
                options.LogoutPath = "/Admin/User/Logout";
            });




            services.AddSession();

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddTransient<IDbContext, YesDbContext>();

            services.AddTransient<IUserService, UserService>();
 

            services.AddTransient(typeof(IRepository<>), typeof(EfRepository<>));

            services.AddHttpContextAccessor();

            services.AddMvc(options => {
                // options.Filters.Add(typeof(YesAuthorizeFilter));
                options.Filters.Add(new GlobalActionFilterAttribute());
            })
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            services.Configure<WebEncoderOptions>(options =>
            {
                options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseStaticHttpContext();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapAreaRoute(name: "areaAdmin", areaName: "Admin", template: "Admin/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(name: "default", template: "{Controller=Home}/{action=Index}/{id?}");


            });
        }
    }
}
